<html>
<head>
<title>钥匙管理</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="shortcut icon" href="/static/images/lock.png" type="image/x-icon">
<link rel="stylesheet" href="/static/css/stylemain.css">
<link rel="stylesheet" href="/static/layui/css/layui.css">

<link rel="stylesheet" href="/static/layui/css/treeTable.css">
<link rel="stylesheet" href="/static/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
<script src="/static/layui/layui.all.js"></script>
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script type="text/javascript" src="/static/js/base64.js"></script>
</head>
<body>
<div class="layui-form">
  <table class="layui-hide" id="tbl_keys" lay-filter="tbl_keys"></table>
  <div id="page"></div>
  <script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon layui-icon-add-circle"></i> 添加</button>
    <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i> 删除</button>
    <button class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon layui-icon-edit"></i> 编辑</button>
	<button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="offkey"><i class="layui-icon layui-icon-404"></i> 注销</button>
	<input style="width:150px;height:24px;font-size: 12px;" id="orgsearch" class="ckinput" type="text" placeholder="机构名称查询"></input>
	<input style="width:150px;height:24px;font-size: 12px;margin-left:5px" id="ownersearch" class="ckinput" type="text" placeholder="使用人查询"></input>
	<input style="width:150px;height:24px;font-size: 12px;margin-left:5px" id="keysnsearch" class="ckinput" type="text" placeholder="识别码查询"></input>
	<button type="button" id="btn_search" style="margin-left:5px" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="search"><i class="fa fa-search" aria-hidden="true"></i>查询</button>
  </div>
  </script>
</div>
<input id="org_id" type="text" name="orgid" style="display:none"></input>

<script id="keyadd" type="text/html">
	<form class="layui-form layui-form-pane" action="" style="margin:20px 20px;width:360px">
		<div class="layui-form-item">
		    <label class="layui-form-label">钥匙识别码</label>
		    <div class="layui-input-block">
		      <input type="text" id="keysn" name="keysn" lay-verify="required" lay-reqtext="识别码是必填项，岂能为空？" placeholder="请输入" autocomplete="off" class="layui-input">
		    </div>
		  </div>
		  <div class="layui-form-item" id = "div_orgname">
	    	<label class="layui-form-label">所属机构</label>
		    <div class="layui-input-block">
		      <input type="button" id="f_orgname" name="orgname" onclick="dialog_orgselect()" class="layui-input" style="text-align: left;">
		    </div>
	  	 </div>
		  <div class="layui-form-item">
	    	<label class="layui-form-label">使用人</label>
		    <div class="layui-input-block">
		      	<button type="button" id="owner" name="owner" onclick="dialog_ownerselect()" class="layui-input" style="text-align: left;"></button>
		    </div>
	  	</div>				
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">备注</label>
		    <div class="layui-input-block">
		      <input type="text" id="descriptor" name="descriptor" autocomplete="off" class="layui-input">
		    </div>
	  	</div>			  	 
	</form>
</script>
<script id="authtable" type="text/html">
	<table class="layui-hide" id="tbl_auth" lay-filter="tbl_auth"></table>
</script>
<script type="text/javascript">
var table = layui.table;
var laypage = layui.laypage;
var form = layui.form;
var curopt = "";
var _currpage = 1;
var _pageSize = 20;
var _orgname = "";
var _owner = [];
var _sorgname = "";
var _sowner = "";
var _skeysn = "";

layui.use([], function(){
	getData(_currpage,_pageSize,"","","");
	
	//监听行工具事件
	table.on('tool(tbl_keys)', function(obj){
	    var data = obj.data;

	});
	form.render('select');
});


$('#ckpassword').on('keydown', function (event) {
    if (event.keyCode == 13) {
    	userckopt();
		layer.closeAll();
    }
});


function dialog_add(){
	_owner = [];
	var win = layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "新增钥匙" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['400px', '360px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#keyadd").html()     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     var mask = $(".layui-layer-shade");
			     mask.appendTo(layero.parent());
			     //其中：layero是弹层的DOM对象
			     $('#keysn').removeAttr("disabled");
			     //$('#owner').removeAttr("disabled");
			     //$('#f_orgname').removeAttr("disabled");
			     $('#owner').val("");
			     $('#f_orgname').val(_orgname);
			     form.render();
			}
		,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	//debugger;
		    	submitForm('','');
			 	 
		  }
		  ,btn2: function(index, layero){
		    //按钮【按钮二】的回调
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
		 }
	});
}

function ckdialgo_auth(){
	layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "复核" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '260px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#dlgck")     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     //var mask = $(".layui-layer-shade");
			     //mask.appendTo(layero.parent());
			     $('#ckname').focus();
			     //其中：layero是弹层的DOM对象
			}
		 ,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	userckopt();
	    		$("#dlgck").css('display','none');
			 	layer.close(index);
		    	
			 	 
		  }
		  ,btn2: function(index, layero){
		    	//按钮【按钮二】的回调
		    
		    	$("#dlgck").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    $("#dlgck").css('display','none'); 
			    
		 }
	});
}

function submitForm(ckname,ckpassword){
	if($('#org_id').val().length < 3 || $('#f_orgname').val().length < 2){
		layer.msg("请选择所属机构!");
		return;
	}
	if($('#keysn').val().replace(/\s+/g,"").length < 1){
		layer.msg("请填写识别码!");
		return false;
	}

	if($('#owner')[0].innerHTML.length < 2){
		layer.msg("请选择使用人!");
		return false;
	}

	debugger;
	var datastring = '{"keysn":"'+$('#keysn').val().replace(/\s+/g,"")+'","owner":"' + _owner[0].username +'","orgid":"' + $('#org_id').val()
	+'","descriptor":"' + $('#descriptor').val()+  '","rname":"智能锁管理/钥匙管理/新增编辑","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';

	$.ajax({
		type:"post",
		contentType: "application/json;charset=UTF-8",
		url: "keyadd",
		async:false,
		data:datastring,
     	dataType:"json",
        success: function(msg) {    //数据提交成功时返回数据
        	//debugger;
        	if(msg.status == "1"){
        		//clearForm();
        		getData(_currpage,_pageSize,_sorgname,_skeysn,_sowner);
        		layer.closeAll();
        	}else if(msg.status == "1211"){

        		$('#ckname').val('');
				$('#ckpassword').val('');
				ckdialgo_auth();
        		
        	}else{
        		layer.msg(msg.desc);
        	}						
        },
        error : function(e){
            alert(e.status);
            alert(e.responseText);
        }

	});		
}


function clearForm(){
	$("#keysn").val('');
	$("#owner").val('');
	$("#descriptor").val('');;
}


table.on('toolbar(tbl_keys)', function(obj){
	//debugger;
	var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
      case 'add':
    	  curopt = 'add';
    	  dialog_add();
      break;
      case 'del':
    	//debugger;
    	curopt = "del";
    	if(checkStatus.data.length == 0){
    		layer.msg('请先选择钥匙!');
    		return;
    	}
        u_remove('','');
      break;
      case 'edit':
    	  if(checkStatus.data.length == 0){
      		layer.msg('请先选择钥匙!');
      		return;
      	  }
    	  curopt = 'edit';
    	  dialog_edit('','',checkStatus.data[0]);
      break;  
      case 'offkey':
    	  if(checkStatus.data.length == 0){
      		layer.msg('请先选择钥匙!');
      		return;
      	  }
    	  curopt = 'offkey';
    	  u_offlock('','');
      break;  
      case 'search':
    	  curopt = 'search';
    	  debugger;
    	  _currpage = 1;
    	  _sorgname = $('#orgsearch').val().replace(/\s+/g,"");
    	  _sowner = $('#ownersearch').val().replace(/\s+/g,"");
    	  _skeysn = $('#keysnsearch').val().replace(/\s+/g,"");
    	  getData(_currpage,_pageSize,_sorgname,_skeysn,_sowner);
      break; 
    };
    
  });

function getData(pageNumber,pageSize,orgname,keysn,owner){

	var datastring = '{"pageNumber":'+pageNumber+',"pageSize":'+ pageSize + ',"orgname":"' + orgname + '","keysn":"' + keysn + '","owner":"' + owner + '"}';

	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getkeylist",
		type : "post",
		data : datastring,
		dataType : "json",
		success : function(msg) {
			debugger;
			tablerender(msg);
			page(msg);
		},
        error : function(e){
        	//dispalyEasyUILoad();
            alert(e.status);
            alert(e.responseText);
        }
	});
}

function tablerender(data){	
	table.render({
		  elem: '#tbl_keys'
		  ,toolbar: '#toolbarDemo'
		  ,cellMinWidth: 50
		  ,cols: [
			  [
			  {type:'radio', hide: true}
		    ,{field:'keysn', title: '识别码'} 
		    ,{field:'createname', title: '创建人', width:100}
		    ,{field:'regdate', title: '创建时间', width:180}
		    ,{field:'ownername', title: '使用人', width:140}
		    ,{field:'orgname', title: '所属机构'}	    
		    ,{field:'electricity', title: '电量(%)', width:100, templet: '#electricityTpl'}	
		    ,{field:'lastreport', title: '最后上报时间', width:180}
		    ,{field:'descriptor', title: '备注'}
		  ]
			  ]
		  ,data:data.datalist
		  ,limit: data.pageSize
		  ,height: parent.iframeH - 60,
		  done: function(res, curr, count){
			  debugger;
		    $('#orgsearch').val(_sorgname);
		    $('#keysnsearch').val(_skeysn);
		    $('#ownersearch').val(_sowner);
		  }
		});	
	
	table.on('row(tbl_keys)', function(obj){
	    var data = obj.data;    
	    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
		//选中radio样式
		obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
	});
}

function numpage(pageNumber, pageSize) {
	var datastring = '{"pageNumber":'+pageNumber+',"pageSize":'+ pageSize + ',"orgname":"' + _sorgname + '","keysn":"' + _skeysn + '","owner":"' + _sowner + '"}';
	//EasyUILoad();
	//debugger;
	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getkeylist",
		type : "post",
		data : datastring,
		dataType : "json",
		success : function(msg) {
			//debugger;
			tablerender(msg);
		},
        error : function(e){
        	//dispalyEasyUILoad();
            alert(e.status);
            alert(e.responseText);
        }
	});
}

function page(data) {
    laypage.render({
        elem: 'page', //注意，这里的 page 是 ID，不用加 # 号
        count: data.totalCount, //数据总数，从服务端得到
        limit: data.pageSize,  // 每页条数
        limits: [10, 20, 30, 40, 50],
        layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
        curr: _currpage,
        jump: function (obj, first) {
            //console.log(obj)
            //obj包含了当前分页的所有参数，比如：
            //layer.msg(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
            //console.log(obj.limit); //得到每页显示的条数

            //首次不执行
            if (!first) {
                //do something
                _currpage = obj.curr;
                _pageSize = obj.limit;
                numpage(obj.curr, obj.limit)  // 分页点击传参 
            }
        }
    });
    form.render(); 
}

function dialog_edit(ckname,ckpassword,data){	
	//获取钥匙使用人信息
	_owner = [];
	var keydata = table.checkStatus('tbl_keys');
	var owerjson = {};
	owerjson['username'] = keydata.data[0].owner;
	owerjson['oper_reals'] = keydata.data[0].ownername;
	_owner.push(owerjson);
	var win = layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "编辑钥匙" //标题
		  ,skin:""   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['400px', '360px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#keyadd").html()     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     var mask = $(".layui-layer-shade");
			     mask.appendTo(layero.parent());
			     //其中：layero是弹层的DOM对象
			     $("#keysn").val(data.keysn);
			 	 $("#owner")[0].innerHTML = data.ownername;
			 	 $("#f_orgname").val(data.orgname);
			 	 $("#descriptor").val(data.descriptor);
			 	 $("#org_id").val(data.orgid);
			 	 
			     $('#keysn').attr("disabled","disabled");
			     //$('#f_orgname').attr("disabled","disabled");
			     //$('#owner').attr("disabled","disabled");
			     form.render(); 
			}
		,yes: function(index, layero){
		    //按钮【按钮一】的回调		    	
		    	u_edit('','');
			 	 
		  }
		  ,btn2: function(index, layero){
		    //按钮【按钮二】的回调
		    
		    	//$("#useradd").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    //$("#useradd").css('display','none'); 
			    
		 }
	});
}

function u_edit(ckname,ckpassword){
	debugger;
	var datastring = '{"keysn":"'+$('#keysn').val() +'","owner":"' + _owner[0].username +'","org_id":"' + $('#org_id').val() + '","descriptor":"' + $('#descriptor').val() + '","rname":"智能锁管理/钥匙管理/新增编辑","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
	$.ajax({
		type:"post",
		contentType: "application/json;charset=UTF-8",
		url: "keyedit",
		async:false,
		data:datastring,
     	dataType:"json",
        success: function(msg) {    //数据提交成功时返回数据
        	if(msg.status == "1"){        		
        		getData(_currpage,_pageSize,_sorgname,_skeysn,_sowner);
        		layer.closeAll();
        		$("#keyadd").css('display','none');
        	}else if(msg.status == "1211"){
        		$('#ckname').val('');
				$('#ckpassword').val('');
				ckdialgo_auth();
        	}else{
        		layer.msg(msg.desc);
        	}						
        },
        error : function(e){
            alert(e.status);
            alert(e.responseText);
        }

	});	
}
  
function u_remove(ckname,ckpassword){	
	var userdata = table.checkStatus('tbl_keys');
	var row = userdata.data[0];
	if (row){
		//debugger;
		var datastring = '{"keysn":"'+row.keysn + '","rname":"智能锁管理/钥匙管理/删除","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
		if(ckname == ''){
			layer.confirm('确定要删除该钥匙?', {
				  btn: ['确定', '取消'] //可以无限个按钮				  
				}, function(index, layero){
				  //按钮【按钮一】的回调
				  $.ajax({
						type:"post",
						contentType: "application/json;charset=UTF-8",
						url: "keydel",
						async:false,
						data:datastring,
				     	dataType:"json",
				        success: function(msg) {    //数据提交成功时返回数据
							if(msg.status == "1"){
								layer.closeAll();
								getData(_currpage,_pageSize,_sorgname,_skeysn,_sowner);									
							}else if(msg.status == "1211"){
								$('#ckname').val('');
								$('#ckpassword').val('');
								//debugger;
								ckdialgo_auth();
				        		
							}else{
								layer.msg(msg.desc);
							}						
							
				        },
				        error : function(e){
				            alert(e.status);
				            alert(e.responseText);
				        }

					});	
					
				}, function(index){
					layer.closeAll();
				});			
		}else{
			
			$.ajax({
				type:"post",
				contentType: "application/json;charset=UTF-8",
				url: "keydel",
				async:false,
				data:datastring,
		     	dataType:"json",
		        success: function(msg) {    //数据提交成功时返回数据
					if(msg.status == "1"){
						getData(_currpage,_pageSize,_sorgname,_skeysn,_sowner);
					}else if(msg.status == "1211"){
						$('#ckname').val('');
						$('#ckpassword').val('');
						ckdialgo_auth();
					}else{
						layer.msg(msg.desc);
					}						
					
		        },
		        error : function(e){
		            alert(e.status);
		            alert(e.responseText);
		        }

			});
		}
							
	}else{
		layer.msg('需选择钥匙!');
	}							
}

function u_offlock(ckname,ckpassword){	
	var userdata = table.checkStatus('tbl_keys');
	var row = userdata.data[0];
	if (row){
		//debugger;
		var datastring = '{"keysn":"' + row.keysn + '","rname":"智能锁管理/钥匙管理/注销","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'"}';
		if(ckname == ''){
			layer.confirm('确定要注销该钥匙?', {
				  btn: ['确定', '取消'] //可以无限个按钮				  
				}, function(index, layero){
				  //按钮【按钮一】的回调
					$.ajax({
						type:"post",
						contentType: "application/json;charset=UTF-8",
						url: "keyoff",
						async:false,
						data:datastring,
				     	dataType:"json",
				        success: function(msg) {    //数据提交成功时返回数据
							if(msg.status == "1"){
								layer.closeAll();
								getData(_currpage,_pageSize,_sorgname,_skeysn,_sowner);									
							}else if(msg.status == "1211"){
								$('#ckname').val('');
								$('#ckpassword').val('');
								//debugger;
								ckdialgo_auth();
				        		
							}else{
								layer.msg(msg.desc);
							}						
							
				        },
				        error : function(e){
				            alert(e.status);
				            alert(e.responseText);
				        }

					});	
				}, function(index){
					layer.closeAll();
					
				});			
		}else{
			
			$.ajax({
				type:"post",
				contentType: "application/json;charset=UTF-8",
				url: "keyoff",
				async:false,
				data:datastring,
		     	dataType:"json",
		        success: function(msg) {    //数据提交成功时返回数据
					if(msg.status == "1"){
						getData(_currpage,_pageSize,_sorgname,_skeysn,_sowner);
					}else if(msg.status == "1211"){
						$('#ckname').val('');
						$('#ckpassword').val('');
						ckdialgo_auth();
					}else{
						layer.msg(msg.desc);
					}						
					
		        },
		        error : function(e){
		            alert(e.status);
		            alert(e.responseText);
		        }

			});
		}
							
	}else{
		layer.msg('需选择钥匙!');
	}							
}

function userckopt(){
	//debugger;
	var ckname = $('#ckname').val();
	if(ckname == ''){
		layer.msg('请填写用户账号!');
		return;
	}
	var ckpassword = $('#ckpassword').val();
	if(curopt == "add"){
		submitForm(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "edit"){
		u_edit(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "del"){
		u_remove(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "offkey"){
		u_offlock(ckname,$.base64.encode(ckpassword));
	}		
}

function userckopt_cancel(){
	$('#ckname').val('');
	$('#ckpassword').val('');	
}

function dialog_orgselect(){
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择机构" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '400px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'getorgtree'     //内容
		  ,btn: ['取消']
		  ,success:function (layero,index) {
			  debugger;
	        var iframe = window['layui-layer-iframe' + index];              
	        iframe.child("keymanage_org","porg");
		  }	  
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
			 	 //$("#orgtree").css('display','none'); 
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
			    //$("#orgtree").css('display','none'); 
		 }
       });
}

function dialog_ownerselect(){
	debugger;
	if($('#org_id').val() == "" || $('#f_orgname').val() == ""){
  	  layer.msg('请先选择所属机构!');
  	  return;
    }
	
	layer.open({
		  type: 2 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "选择使用人" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['550px', '600px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: 'template_userlist_single'     //内容
		  ,btn: ['确定','取消'] //只是为了演示	
		  ,success:function (layero,index) {
			  
              var iframe = window['layui-layer-iframe' + index];              
              iframe.child(_owner,$('#org_id').val());
      	  }
		  ,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	debugger;
		    	iframeWin = window[layero.find('iframe')[0]['name']];
		    	_owner = iframeWin.getCheckedUsers();	
		    	$('#owner')[0].innerHTML = _owner[0].oper_reals;		    	
			 	layer.close(index);
		  }
		  ,cancel: function(index,layero){ 
			    //右上角关闭回调
		 }
       });
}
</script>
<script type="text/html" id="statusTpl">
  {{#  if(d.active == '0'){ }}	
    <span>正常</span>
  {{#  } else if(d.active == '1') { }}
    <span style="color: #F581B1;">注销</span>
  {{#  } }}
</script>
<script type="text/html" id="electricityTpl">
  {{#  if(d.electricity == '999'){ }}	
    <span>未上报</span>
  {{# }else if(d.electricity <= 20) { }}	
    <span style="color: #F581B1;">{{ d.electricity }}</span>
  {{#  }else { }}
  	<span>{{ d.electricity }}</span>
  {{#  } }}
</script>
</body>
</html>
